package com.yoyo.topscrollview.common;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import java.util.List;

import androidx.recyclerview.widget.RecyclerView;

/**
 * author:yoyo
 * date:2020/6/12
 */
public abstract class CommonAdapter<T> extends RecyclerView.Adapter<CommonViewHolder> {
    protected List<T> data;
    private int layoutId;
    private OnItemClickListener itemClick;
    private OnItemLongClickListener onItemLongClickListener;


    public CommonAdapter(List<T> data, int layoutId) {
        this.data = data;
        this.layoutId = layoutId;
    }

    public CommonAdapter(int layoutId) {
        this.layoutId = layoutId;
    }

    public void setItemClick(OnItemClickListener itemClick) {
        this.itemClick = itemClick;
    }

    public void setItemLongClick(OnItemLongClickListener onItemLongClickListener) {
        this.onItemLongClickListener = onItemLongClickListener;
    }


    public void setData(List<T> list) {
        data = list;
        this.notifyDataSetChanged();
    }

    @Override
    public CommonViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(layoutId, parent, false);
        final CommonViewHolder holder = new CommonViewHolder(view);
        if (itemClick != null) {
            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    itemClick.onItemClick(holder, holder.itemView, holder.getAdapterPosition());
                }
            });
        }
        if (onItemLongClickListener != null) {
            holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    onItemLongClickListener.onItemLongClickListener(holder, holder.itemView, holder.getAdapterPosition());
                    return false;
                }
            });
        }


        return holder;
    }

    @Override
    public void onBindViewHolder(CommonViewHolder holder, int position) {
        bindData(holder, position, data.get(position));

    }

    public abstract void bindData(CommonViewHolder holder, int position, T item);

    @Override
    public int getItemCount() {
        return data != null ? data.size() : 0;
    }


    public interface OnItemClickListener {
        void onItemClick(CommonViewHolder holder, View view, int position);
    }

    public interface OnItemLongClickListener {
        void onItemLongClickListener(CommonViewHolder holder, View view, int position);
    }


    public void remove(int position) {
        data.remove(position);
        notifyItemRemoved(position);
    }
}